﻿/*
 * QtPet Online File Manager v1.0
 * Copyright (c) 2009, Zhifeng Lin (fszlin[at]gmail.com)
 * 
 * Licensed under the MS-PL license.
 * http://qtfile.codeplex.com/license
 */

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;

using QtFile.Services;

namespace QtFile.FileBased
{
	public class FolderService : FileBasedService, IFolderService
	{
		public FolderService(string rootPath, string username, bool encodeUserName, char directorySeparator)
			: base(rootPath, username, encodeUserName, directorySeparator)
		{
		}

		public OpResult Create(string path)
		{
			string fullPath = RootFolder.GetPath(path);
			if (Directory.Exists(fullPath))
				return OpResult.AlreadyExist;
			Directory.CreateDirectory(fullPath);
			return OpResult.Succeed;
		}

		public OpResult Move(string srcPath, string destPath)
		{
			srcPath = RootFolder.GetPath(srcPath);
			destPath = RootFolder.GetPath(destPath);

			if (!Directory.Exists(srcPath))
				return OpResult.NotFound;

			if (!Directory.Exists(Path.GetDirectoryName(destPath)))
				return OpResult.FolderNotFound;

			if (Directory.Exists(destPath))
				return OpResult.AlreadyExist;

			Directory.Move(srcPath, destPath);
			return OpResult.Succeed;
		}

		public OpResult Delete(string path)
		{
			string fullPath = RootFolder.GetPath(path);
			if (!Directory.Exists(fullPath))
				return OpResult.NotFound;

			Directory.Delete(fullPath, true);
			return OpResult.Succeed;
		}

		public IEnumerable<UserFolder> GetAllFolders()
		{
			int rootPathLen = RootFolder.RootPath.Length + 1;

			return Directory.GetDirectories(RootFolder.RootPath, "*", SearchOption.AllDirectories)
				.Select(p => new UserFolder() { Path = ResolvePathResult(p) });
		}

		public int Count()
		{
			return RootFolder.CountFolders();
		}
	}
}
